<?php
/**
 * ExaminationType Service.
 * User: Administrator
 * Date: 2020/2/13 0013
 * Time: 下午 2:02
 */
namespace app\api\service\order;

use app\api\model\order\Order as OrderModels;
use app\api\model\curriculum\Curriculum;
use app\api\model\user\UserCoupons;
use app\exceptions\OrdinaryException;
use think\Db;

Class Order {

    /**
     * 下单
     * @param array $data
     * @throws OrdinaryException
     * @return mixed
     */
    public function set( array $data )
    {
        $curriculum = Curriculum::get($data['id']);
        if ( null === $curriculum ) {
            throw new OrdinaryException('课程已不存在');
        }
        $lists = [];
        $lists['price'] = $curriculum->price;
        Db::startTrans();
        if ( $data['cid'] ) {
            $userCoupons = UserCoupons::with(['coupons'=>function($query)use($curriculum){
                $date = date("Y-m-d");
                $query->where('start_date','<=', $date)->where('end_date','>=', $date)->where('available','<', $curriculum->price)
                    ->where('(find_in_set(0,type) or find_in_set(1,type))');
            }])->where('cid',$data['cid'])->where('status',0)->findOrEmpty();
            if ( true === $userCoupons->isEmpty() ) {
                Db::rollback();
                throw new OrdinaryException('您使用的优惠券不存在');
            }
            if ( !$userCoupons->coupons ) {
                Db::rollback();
                throw new OrdinaryException('该优惠券已不可用');
            }
            $lists['coupon_id'] = $data['cid'];
            $lists['price'] -= $userCoupons->coupons->price;
            $userCoupons->status = 1;
            if ( $userCoupons->save() === false ) {
                Db::rollback();
                throw new OrdinaryException('优惠券错误');
            }
        }
        if ( $lists['price'] != $data['total'] ) {
            Db::rollback();
            throw new OrdinaryException('产品价格已改变');
        }
        $lists['curriculum_id'] = $data['id'];
        $lists['curriculum_title'] = $curriculum->name;
        $lists['order_number'] = date("YmdHis").rand(1111,9999);
        $order = OrderModels::create($lists);
        if ( $order->isEmpty() ) {
            Db::rollback();
            throw new OrdinaryException('下单失败');
        }
        Db::commit();
        return $order;
    }

    /**
     * 获取订单列表
     *
     * @return mixed
     */
    public function lists()
    {
        $order = OrderModels::with(['curriculum'=>function($query){
            $query->append(['type_text']);
        }])->order('id', 'desc')->selectOrFail()->append(['payment_status_text','create_at_text']);
        foreach ( $order as $_order ) {
            if ( $_order->payment_status == 0 && strtotime($_order->create_at)+60*30 <= time() ) {
                $_order->payment_status = 2;
                $_order->save();
            } else {
                $_order->paytime = date("m.d H:i", strtotime($_order->create_at)+60*30);
            }
        }
        return $order;
    }

    /**
     * 获取订单详情
     * @param int $id
     * @return mixed
     */
    public function read(int $id)
    {
        return OrderModels::with(['curriculum'=>function($query){
            $query->append(['type_text','start_cycle_text','end_cycle_text']);
        }])->getOrFail($id)->append(['payment_status_text','create_at_text']);
    }

    /**
     * 取消订单
     * @param int $id
     * @throws OrdinaryException
     * @return boolean
     */
    public function cancel( int $id )
    {
        $model = OrderModels::getOrFail($id);
        if ( $model->payment_status != 0 ) {
            throw new OrdinaryException('该订单已为取消状态');
        }
        $model->payment_status = 2;
        return $model->save();
    }

    /**
     * 获取我的课程
     *
     * @return mixed
     */
    public function mineCurriculum()
    {
        return OrderModels::with(['curriculum'=>function($query){
            $query->append(['type_text','start_cycle_text','end_cycle_text']);
        }])->where('payment_status', 1)->order('id', 'desc')->selectOrFail();
    }

}